﻿using System;
using System.Web.UI.HtmlControls;
using System.Xml;

namespace KPI.Controls
{
	public partial class SiteMenu : System.Web.UI.UserControl
	{
		public DataAccess.Models.LoginUserInfo TheCurrentLoginUser
		{
			get
			{
				return KPISiteContext.Current.CurrentUser;
			}
		}

		protected void Page_Load(object sender, EventArgs e)
		{

			if(TheCurrentLoginUser != null)
			{
				BuildMenu();
			}

		}

		private XmlDocument GetMenuDoc()
		{
			XmlDocument result = null;

			try
			{
				if(Cache["sitemenudoc"] == null)
				{
					var doc = new XmlDocument();
					doc.Load(Server.MapPath("/") + "SiteMenu.xml");

					Cache.Add("sitemenudoc", doc, new System.Web.Caching.CacheDependency(Server.MapPath("/") + "SiteMenu.xml"), System.Web.Caching.Cache.NoAbsoluteExpiration, new TimeSpan(4, 0, 0), System.Web.Caching.CacheItemPriority.Default, null);
				}

				result = Cache["sitemenudoc"] as XmlDocument;
			}
			catch
			{
				throw;
			}

			return result;
		}

		private bool CheckUserRole(string userRole, string roles)
		{
			var result = false;

			if(!string.IsNullOrWhiteSpace(userRole) && !string.IsNullOrWhiteSpace(roles))
			{
				var roleItems = roles.Split(',');

				foreach(var r in roleItems)
				{
					if(r == userRole)
					{
						result = true;
						break;
					}
				}
			}

			return result;
		}

		private void BuildMenu()
		{
			var xmlDoc = GetMenuDoc();

			try
			{
				//xmlDoc.Load(Server.MapPath("/") + "SiteMenu.xml");

				if(xmlDoc.DocumentElement != null && xmlDoc.DocumentElement.HasChildNodes)
				{
					//var u = KPISiteContext.Current.CurrentUser;

					var menuBox = new HtmlGenericControl("div");
					menuBox.Attributes.Add("class", "menubox");

					foreach(XmlNode node in xmlDoc.DocumentElement.ChildNodes)
					{
						var roles = node.Attributes["roles"].Value;

						//if(roles.Equals("*") || CheckUserRole(u.RoleName, roles))
						{
							var menuItem = new HtmlGenericControl("div");
							menuItem.Attributes.Add("class", "menuitem");

							var spanMenuItemBox = new HtmlGenericControl("span");
							if(IsActiveMenu(node))
							{
								spanMenuItemBox.Attributes.Add("class", "menuitembox activeitem");
							}
							else
							{
								spanMenuItemBox.Attributes.Add("class", "menuitembox");
							}
							var menuItemLink = new HtmlAnchor();

							var url = "~/NoPermission.aspx";

							if(roles.Equals("*") || CheckUserRole(TheCurrentLoginUser.RoleName, roles))
							{
								url = node.Attributes["url"].Value;
							}

							var title = node.Attributes["title"].Value;
							var description = node.Attributes["description"].Value;

							menuItemLink.InnerText = title;
							if(title.Equals("邮件"))
							{
								var mailCount = GetUnReadMailCount();

								if(mailCount > 0)
								{
									menuItemLink.InnerText += " (" + mailCount.ToString() + ")";
								}
							}
							menuItemLink.HRef = url;
							menuItemLink.Title = description;

							spanMenuItemBox.Controls.Add(menuItemLink);
							menuItem.Controls.Add(spanMenuItemBox);

							if(node.HasChildNodes)
							{
								var subMenuContainer = new HtmlGenericControl("div");
								subMenuContainer.Attributes.Add("class", "submenucontainer");

								foreach(XmlNode childNode in node.ChildNodes)
								{
									roles = childNode.Attributes["roles"].Value;

									if(roles.Equals("*") || CheckUserRole(TheCurrentLoginUser.RoleName, roles))
									{
										url = childNode.Attributes["url"].Value;
										title = childNode.Attributes["title"].Value;
										description = childNode.Attributes["description"].Value;

										var spanSubMenuItemBox = new HtmlGenericControl("span");
										spanSubMenuItemBox.Attributes.Add("class", "menuitembox");
										var subMenuItemLink = new HtmlAnchor();

										subMenuItemLink.Title = title;
										subMenuItemLink.HRef = url;
										subMenuItemLink.InnerText = title;

										spanSubMenuItemBox.Controls.Add(subMenuItemLink);
										subMenuContainer.Controls.Add(spanSubMenuItemBox);
									}
								}

								menuItem.Controls.Add(subMenuContainer);
							}

							menuBox.Controls.Add(menuItem);
						}
					}

					menucontainer.Controls.Add(menuBox);
				}
			}
			catch
			{
				throw;
			}
		}

		private int GetUnReadMailCount()
		{
			var result = 0;

			//var u = KPISiteContext.Current.CurrentUser;

			if(TheCurrentLoginUser != null)
			{
				using(var mailRepository = new DataAccess.Repository.MailRepository())
				{
					result = mailRepository.GetUnReadMailCount(TheCurrentLoginUser.UserName);
				}
			}

			return result;
		}

		private bool IsActiveMenu(XmlNode node)
		{
			var result = false;

			if(node != null)
			{
				var url = node.Attributes["url"].Value;

				var currentPageName = GetCurrentRequestPage();

				if(url.Contains(currentPageName))
				{
					result = true;
				}

				if(node.HasChildNodes)
				{
					foreach(XmlNode childNode in node.ChildNodes)
					{
						var childUrl = childNode.Attributes["url"].Value;

						if(childUrl.Contains(currentPageName))
						{
							result = true;
							break;
						}
					}
				}
			}

			return result;
		}

		private string GetCurrentRequestPage()
		{
			var result = string.Empty;

			if(Request.Url != null && !string.IsNullOrWhiteSpace(Request.Url.AbsolutePath))
			{
				var absolutePath = Request.Url.AbsolutePath;

				if(absolutePath.Contains("/"))
				{
					var arrPathPart = absolutePath.Split('/');

					result = arrPathPart[arrPathPart.Length - 1];
				}
			}

			return result;
		}
	}
}